package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 支付宝管理
 */
@Controller
@RequestMapping("/api/payment/alipay")
@Slf4j
public class AlipayController {

    @Autowired
    private AlipayService alipayService;

    //  http://payment.gmall.com/api/payment/alipay/refund/ATGUIGU158348294514133
      ///    /api/payment/alipay/refund/ATGUIGU158348294514133
    //退款

    @GetMapping("/refund/{out_trade_no}")
    @ResponseBody
    public String refund(@PathVariable(name = "out_trade_no") String out_trade_no){
        return alipayService.refund(out_trade_no);
    }



    //去支付宝的支付页面
    @GetMapping("/submit/{orderId}")
    @ResponseBody
    public String submit(@PathVariable(name = "orderId") Long orderId){
        return alipayService.createPage(orderId);
    }
    //同步转发到商户的成功页面
    //http://api.gmall.com  /api/payment/alipay  /callback/return
    @GetMapping("/callback/return")
    public String callback(){
        //  http://payment.gmall.com/pay/success.html
        return "redirect:" + AlipayConfig.return_order_url;
    }


    ///api/payment/alipay  /callback/notify  支付宝异步回调 通知
    @PostMapping("/callback/notify")
    @ResponseBody
    public String callbackNotify(@RequestParam Map<String, String> paramsMap) throws AlipayApiException {
        System.out.println("下面的信息是支付宝支付成功之后信息");
        System.out.println("=============================");
        System.out.println(paramsMap);
        //1:验签
        boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap,
                AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        if(signVerified){
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            //交易状态是成功
            if("TRADE_SUCCESS".equalsIgnoreCase(paramsMap.get("trade_status"))
             || "TRADE_FINISHED".equalsIgnoreCase(paramsMap.get("trade_status"))){
                //支付成功  更新支付信息表 更新订单表
                alipayService.paySuccess(paramsMap);

            }


            return "success";
        }else{
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            log.error("验签失败则记录异常日志");
            return "failure";
        }
    }

}
